package session

import (
"fmt"
"sync"
"github.com/looplab/fsm"
"ivr/robot"
)

type Session struct {
	Robot  *robot.Robot
	Fsm     *fsm.FSM
}

type SessionMgr struct{
	Id2SessionMap map[string] *Session
}

var once sync.Once
var pSessionMgr *SessionMgr

func GetSessionMgr() *SessionMgr{
	once.Do( func() {
	pSessionMgr = createSessionMgr()})
	return pSessionMgr
}
func createSessionMgr() *SessionMgr{
	newSessionMgr := new (SessionMgr)
	newSessionMgr.Id2SessionMap = make(map[string] *Session)
	return newSessionMgr
}

/*CreateSession
1,create fsm according to robotId
2,Set Callback
3,
*/
func CreateSession(mgr *SessionMgr,uuid string,pRobot *robot.Robot) *Session{
	//fsm := new (fsm.FSM)
	//* fsm = *pRobot.Fsm
	//fsm := pRobot.Fsm
	fsm := fsm.NewFSM("idle",pRobot.Events,fsm.Callbacks{},)
	fmt.Println(fsm.Current())
	//newSession := &Session{Robot:pRobot,Fsm:fsm}
	newSession := &Session{Robot:pRobot,Fsm:fsm}
	
	//fsm.Event("$start")
	//fmt.Println(fsm.Current())
	mgr.Id2SessionMap[uuid] = newSession
	return newSession;
}	
func GetSession(mgr *SessionMgr,uuid string) * Session{
	pSession, ok := mgr.Id2SessionMap[uuid]	
	fmt.Println(ok)
	return pSession
}
func GetSessionCurState( pSession *Session) string{
	return pSession.Fsm.Current()
}
func Input(pSession *Session, event string) (string){
	pSession.Fsm.Event(event)
	state := pSession.Fsm.Current()
	res := robot.GetResponse(pSession.Robot,robot.GetStateIndex(pSession.Robot,state))	
	return res
}
func ReleaseSession(mgr *SessionMgr,uuid string){

	_, ok := mgr.Id2SessionMap[uuid]	
	if (ok){
		fmt.Printf("Released %s\n",uuid)
		delete(mgr.Id2SessionMap,uuid)
	}
}
